package com.cctc.security.support;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.cctc.framework.util.MD5Util;
import com.cctc.security.domain.User;
import com.cctc.security.services.UserService;

public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

	@Autowired
	private UserService<User> userService;

	private static final String USERNAME = "username";
	private static final String PASSWORD = "password";

	//private static final String VALIDATE_CODE = "validateCode";

	private static final String SESSION_VALUE = "SPRING_SECURITY_LAST_USERNAME";

	//	public MyUsernamePasswordAuthenticationFilter(UserService userService){
	//		this.userService=userService;
	//	}

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws AuthenticationException {
		HttpSession session = request.getSession();
		session.setAttribute("ERROR_USER_NAME", null);
		session.setAttribute("ERROR_PASSWORD", null);
		//检测验证码  
		//checkValidateCode(request);  

		if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}

		String userName = obtainUsername(request);
		String password = obtainPassword(request);
		if ("" == userName) {
			if ("" == password) {
				session.setAttribute("ERROR_USER_NAME", "用户名不得为空");
				session.setAttribute("ERROR_PASSWORD", "密码不得为空");
				throw new AuthenticationServiceException("用户名和密码不得为空");
			}
			request.setAttribute("ERROR_USER_NAME", "用户名不得为空");
			throw new AuthenticationServiceException("用户名不得为空");

		} else {
			if ("" == password) {
				session.setAttribute(SESSION_VALUE, userName);
				session.setAttribute("ERROR_PASSWORD", "密码不得为空");
				throw new AuthenticationServiceException("用户名和密码不得为空");
			}
		}
		password=MD5Util.md5s((userName+password).getBytes());
		//验证用户账号与密码是否对应  
		User user = this.userService.getUserByName(userName.trim());
		if (user == null) {
			session.setAttribute("ERROR_USER_NAME", "用户不存在");
			throw new AuthenticationServiceException("该用户不存在！");
		}
		if (!user.getPassword().equals(password)) {
			session.setAttribute("ERROR_PASSWORD", "密码错误！");
			throw new AuthenticationServiceException("密码错误！");
		}
		session.setAttribute("ERROR_USER_NAME", null);
		session.setAttribute("ERROR_PASSWORD", null);
		session.setAttribute(SESSION_VALUE, userName);
		
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userName, password);
		// 允许子类设置详细属性  
		setDetails(request, authRequest);

		// 运行UserDetailsService的loadUserByUsername 再次封装Authentication  
		return this.getAuthenticationManager().authenticate(authRequest);
	}

	//	 protected void checkValidateCode(HttpServletRequest request) {   
	//	        HttpSession session = request.getSession();  
	//	          
	//	        String sessionValidateCode = obtainSessionValidateCode(session);   
	//	        //让上一次的验证码失效  
	//	        session.setAttribute(VALIDATE_CODE, null);  
	//	        String validateCodeParameter = obtainValidateCodeParameter(request);    
	//	        if (""==validateCodeParameter|| !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {    
	//	            throw new AuthenticationServiceException("验证码错误！");    
	//	        }    
	//	    }  
	//	      
	//	    private String obtainValidateCodeParameter(HttpServletRequest request) {  
	//	        Object obj = request.getParameter(VALIDATE_CODE);  
	//	        return null == obj ? "" : obj.toString();  
	//	    }  
	//	  
	//	    protected String obtainSessionValidateCode(HttpSession session) {  
	//	        Object obj = session.getAttribute(VALIDATE_CODE);  
	//	        return null == obj ? "" : obj.toString();  
	//	    }  

	@Override
	protected String obtainUsername(HttpServletRequest request) {
		String obj = request.getParameter(USERNAME);
		return null == obj ? "" : obj;
	}

	@Override
	protected String obtainPassword(HttpServletRequest request) {
		String obj = request.getParameter(PASSWORD);
		return null == obj ? "" : obj;
	}

}
